package com.atguigu.springcloud.controller;

import com.atguigu.springcloud.entities.CommonResult;
import com.atguigu.springcloud.entities.Payment;
import com.atguigu.springcloud.lb.LoadBalancer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

@RestController
@Slf4j
public class OrderController {

    @Resource
    private RestTemplate restTemplate;

    /**
     * 自定义负载均衡策略类
     */
    @Resource
    private LoadBalancer loadBalancer;

    /**
     * 自定义负载均衡策略相关类
     */
    @Resource
    private DiscoveryClient discoveryClient;

    public static final String PAYMENT_URL = "http://CLOUD-PROVIDER-SERVICE";

    @GetMapping("/comsumer/payment/create")
    public CommonResult<Payment> create(Payment payment){
        String url = PAYMENT_URL+"/payment/create";
        return restTemplate.postForObject(url,payment,CommonResult.class);
    }
    @GetMapping("/comsumer/payment/get/{id}")
    public CommonResult<Payment> getPayment(@PathVariable("id") Long id){
        String url = PAYMENT_URL+"/payment/get/"+id;
        log.info(url);
        return restTemplate.getForObject(url,CommonResult.class);
    }
    @GetMapping("/comsumer/payment/test")
    public CommonResult<Payment> testMapping(){
        return new CommonResult(100,"成功了",null);
    }
    @GetMapping("/comsumer/payment/myselftest")
    public CommonResult<Payment> discovery(){
        String url = PAYMENT_URL+"/payment/myselftest";
        return restTemplate.getForObject(url,CommonResult.class);
    }

    @GetMapping("/consumer/payment/lb")
    public String getPaymentLB(){
        System.out.println("succeed maybe");
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PROVIDER-SERVICE");
        if (instances == null || instances.size() <= 0){
            log.info("null");
            return null;
        }
        ServiceInstance serviceInstance = loadBalancer.instances(instances);
        URI uri = serviceInstance.getUri();
        String url = uri + "/payment/lb";
        System.out.println(url);
        return restTemplate.getForObject(url,String.class);
    }
}
